package com.windbell.net;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;

public class NetTask extends AsyncTask<String, Integer, String> {
	myProcess myProcess;

	public NetTask(myProcess process) {
		this.myProcess = process;
	}

	@Override
	protected void onPostExecute(String result) {
		myProcess.process(result);
		super.onPostExecute(result);
	}

	@Override
	protected String doInBackground(String... params) {
		try {
			HttpClient client = new DefaultHttpClient();
			// params[0]代表连接的url
			HttpGet get = new HttpGet(params[0]);
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			long length = entity.getContentLength();
			InputStream is = entity.getContent();
			String s = null;
			if (is != null) {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buf = new byte[128];
				int ch = -1;
				int count = 0;
				while ((ch = is.read(buf)) != -1) {
					baos.write(buf, 0, ch);
					count += ch;
					if (length > 0) {
						// 如果知道响应的长度，调用publishProgress（）更新进度
						// publishProgress((int) ((count / (float) length) *
						// 100));
					}
				}
				s = new String(baos.toByteArray());
			}
			return s;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public interface myProcess {
		public void process(String result);
	}
}
